package org.example.myleet.p594;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Solution {

    public int findLHS(int[] nums) {
        Arrays.sort(nums);
        int maxLen = 0;
        int last = nums[0], lastLen = 1, cur, curLen = 0, i = 1;
        while (i < nums.length && last == nums[i]) {
            ++lastLen;
            ++i;
        }
        for (; i < nums.length; ++i) {
            cur = nums[i++];
            curLen = 1;
            while (i < nums.length && cur == nums[i]) {
                ++curLen;
                ++i;
            }
            --i;
            if (cur - last == 1) {
                maxLen = Math.max(maxLen, lastLen + curLen);
            }
            last = cur;
            lastLen = curLen;
        }
        return maxLen;
    }

    public int findLHS_(int[] nums) {
        Map<Integer, Integer> numCount = new HashMap<>();
        for (int num : nums) {
            numCount.put(num, numCount.getOrDefault(num, 0) + 1);
        }
        int maxLen = 0;
        for (int num : nums) {
            Integer num_;
            if (Objects.nonNull(num_ = numCount.get(num - 1))) {
                maxLen = Math.max(maxLen, numCount.get(num) + num_);
            }
            if (Objects.nonNull(num_ = numCount.get(num + 1))) {
                maxLen = Math.max(maxLen, numCount.get(num) + num_);
            }
        }
        return maxLen;
    }
}
